using B.S.BaseData.Infrastructure;
using B.S.BaseData.ReadAPI.Extensions;
using B.S.BaseData.ReadAPI.Utils;
using CSRedis;
using Lazy.Captcha.Core;
using Lazy.Captcha.Core.Generator;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using NLog.Web;
using ServiceManagement.Consul;
using Yitter.IdGenerator;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

//配置数据库
builder.Services.AddDbContext<BaseDbContext>(d =>
{
    d.UseSqlServer(builder.Configuration.GetConnectionString("con"));

});

/*//用法1-CSRedisClient实例化的对象
var rds = new CSRedis.CSRedisClient(builder.Configuration.GetConnectionString("RedisStr"));
builder.Services.AddSingleton(rds);   //注册成全局单例*/

//使用 AddSingleton 的工厂方法 实例一个客户端对象
builder.Services.AddSingleton<CSRedisClient>(provider =>
    new CSRedisClient(builder.Configuration.GetConnectionString("RedisStr")));


builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(d =>
{
    //读取xml文件 api注释
    string xml = AppContext.BaseDirectory + "B.S.BaseData.ReadAPI.xml";
    d.IncludeXmlComments(xml, true);

    //定义一个Swagger文档 Users组
    d.SwaggerDoc("Users", new OpenApiInfo { Title = "Users API", Version = "用户管理" });
    //定义第二个Swagger文档 Roles组
    d.SwaggerDoc("Roles", new OpenApiInfo { Title = "Roles API", Version = "角色管理" });
    d.SwaggerDoc("Depts", new OpenApiInfo { Title = "Depts API", Version = "部门管理" });
    d.SwaggerDoc("Perms", new OpenApiInfo { Title = "Perms API", Version = "权限管理" });
    d.SwaggerDoc("MeetingRoom", new OpenApiInfo { Title = "MeetingRoom API", Version = "会议室管理" });
    d.SwaggerDoc("MeetingReservation", new OpenApiInfo { Title = "MeetingReservation API", Version = "会议室预约管理" });
    d.SwaggerDoc("MeetingApproval", new OpenApiInfo { Title = "MeetingApproval API", Version = "会议室审批管理" });
    d.SwaggerDoc("OperationLog", new OpenApiInfo { Title = "OperationLog API", Version = "日志管理" });


    //配置文档包含的规则
    //如果没有指定GroupName，则默认使用ControllerName进行分组
    //DocInclusionPredicate用于控制那些api描述应该包含在哪个swagger文档中
    d.DocInclusionPredicate((docName, apiDesc) =>
    {
        var groupName = apiDesc.GroupName ?? apiDesc.ActionDescriptor.RouteValues["controller"];
        //如果文档名称和groupname相同，则包含该api
        return docName == groupName;
    });

    // 注册自定义的 SchemaFilter 来处理默认值
    d.SchemaFilter<DefaultValueSchemaFilter>();


});



// ����Swagger/OpenAPI
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//JWT
builder.Services.AddJwt(builder);


//注册服务
builder.Services.AddServices();

// 默认使用内存存储（AddDistributedMemoryCache）
builder.Services.AddCaptcha(builder.Configuration);
// 全部配置
builder.Services.AddCaptcha(builder.Configuration, option =>
{
    option.CaptchaType = CaptchaType.WORD; // 验证码类型
    option.CodeLength = 4; // 验证码长度, 要放在CaptchaType设置后.  当类型为算术表达式时，长度代表操作的个数
    option.ExpirySeconds = 30; // 验证码过期时间
    option.IgnoreCase = true; // 比较时是否忽略大小写
    option.StoreageKeyPrefix = ""; // 存储键前缀

    option.ImageOption.Animation = false; // 是否启用动画
    option.ImageOption.FrameDelay = 30; // 每帧延迟,Animation=true时有效, 默认30

    option.ImageOption.Width = 150; // 验证码宽度
    option.ImageOption.Height = 50; // 验证码高度
    option.ImageOption.BackgroundColor = SkiaSharp.SKColors.White; // 验证码背景色

    option.ImageOption.BubbleCount = 2; // 气泡数量
    option.ImageOption.BubbleMinRadius = 5; // 气泡最小半径
    option.ImageOption.BubbleMaxRadius = 15; // 气泡最大半径
    option.ImageOption.BubbleThickness = 1; // 气泡边沿厚度

    option.ImageOption.InterferenceLineCount = 2; // 干扰线数量

    option.ImageOption.FontSize = 36; // 字体大小
    option.ImageOption.FontFamily = DefaultFontFamilys.Instance.Actionj; // 字体

    /* 
     * 中文使用kaiti，其他字符可根据喜好设置（可能部分转字符会出现绘制不出的情况）。
     * 当验证码类型为“ARITHMETIC”时，不要使用“Ransom”字体。（运算符和等号绘制不出来）
     */

    option.ImageOption.TextBold = true;// 粗体，该配置2.0.3新增
});



//转换大小写
builder.Services.AddControllers().AddJsonOptions(d => d.JsonSerializerOptions.PropertyNamingPolicy = null);




builder.Host.UseNLog();


//consul
builder.Configuration.Register();



// Swagger
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<TokenHelper>();

// 注册 jwt 认证服务
builder.Services.AddSingleton<System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler>();

// 注册自定义的 TokenHelper
builder.Services.AddScoped<TokenHelper>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(x =>
    {
        //为每个分组配置不同的Swagger文档
        x.SwaggerEndpoint("/swagger/Users/swagger.json", "Users API 用户管理");
        x.SwaggerEndpoint("/swagger/Roles/swagger.json", "Roles API 角色管理");
        x.SwaggerEndpoint("/swagger/Depts/swagger.json", "Depts API 部门管理");
        x.SwaggerEndpoint("/swagger/Perms/swagger.json", "Perms API 权限管理");
        x.SwaggerEndpoint("/swagger/MeetingRoom/swagger.json", "MeetingRoom API 会议室管理");
        x.SwaggerEndpoint("/swagger/MeetingReservation/swagger.json", "MeetingReservation API 会议室预约管理");
        x.SwaggerEndpoint("/swagger/MeetingApproval/swagger.json", "MeetingApproval API 会议室审批管理");
        x.SwaggerEndpoint("/swagger/OperationLog/swagger.json", "OperationLog API 日志管理");
        //x.SwaggerEndpoint("/swagger/v2/swagger.json", "Roles API V2");
        //x.RoutePrefix = string.Empty; // 设置 Swagger UI 在根路径下可访问
    });
}

// 鉴权
app.UseAuthentication();

app.UseAuthorization();


//跨域
app.UseCors(d => d.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());

//配置静态文件中间件
app.UseStaticFiles();

// jwt中间件
app.UseMiddleware<CustomAuthorizationMiddleware>();

//雪花算法
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());

app.UseAuthorization();

app.MapControllers();

app.Run();
